package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import com.hmall.pojo.Item;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IItemService itemService;

    /**
     * 根据id查找返回对象
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item findById(@PathVariable("id") Long id){
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 减少库存
     * @param itemId
     * @param num
     * @return
     */
    @PutMapping("/stock/{itemId}/{num}")
    public Integer updateByNum(@PathVariable("itemId") Long itemId,@PathVariable("num") Integer num){
        Integer count = itemService.updateByNum(itemId,num);
        return count;
    }

    @Resource
    private ItemMapper itemMapper;

    @GetMapping("/list")
    public PageDTO list( Integer page ,Integer size) {
        Page<Item> pageDTO = itemService.page(new Page<>(page, size));
        return new PageDTO(pageDTO.getTotal(), pageDTO.getRecords());
    }

    @PostMapping()
    public void add(@RequestBody Item item) {
        itemMapper.insert(item);
        rabbitTemplate.convertAndSend("hmall.topic","insert.update",item.getId());
    }

    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable String id, @PathVariable Integer status) {
        Item byId = itemService.getById(id);
        byId.setStatus(status);
        itemMapper.updateById(byId);

        rabbitTemplate.convertAndSend("hmall.topic","insert.update",byId.getId());

    }

    @PutMapping()
    public void update(@RequestBody Item item) {
        itemService.updateById(item);

        rabbitTemplate.convertAndSend("hmall.topic","insert.update",item.getId());
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable String id) {
        itemService.removeById(id);
        rabbitTemplate.convertAndSend("hmall.topic","delete.delete",id);
    }

    @GetMapping("/count")
    public Integer count() {
       return itemService.count();
    }
}
